import UpdateModal from '@/pages/Admin/User/components/UpdateModal';
import { deleteUserUsingPost, listUserByPageUsingPost,exportExcelUserUsingPost } from '@/services/backend/userController';
import type { ActionType, ProColumns} from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { message, Space, Typography,Popconfirm,Table } from 'antd';
import React, { useRef, useState } from 'react';

/**
 * 用户管理页面
 *
 * @constructor
 */
const UserAdminPage: React.FC = () => {
  // 是否显示更新窗口
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  // 当前用户点击的数据
  const [currentRow, setCurrentRow] = useState<API.User>();
  //选择的数据
  const [selectRows, setSelectRows] = useState<Array<API.User>>();
  const [selectId, setSelectId] = useState([]);

  // 批量删除用户
  const handleDelete = async (row: Array<number>) => {
    const hide = message.loading('正在删除');
    if (!row) return true;
    try {
      const res = await deleteUserUsingPost({
        id: row,
      });
      hide();
      message.success(res.message);
      actionRef?.current?.reload();
      return true;
    } 
    catch (error: any) {
      hide();
      return false;
    }
  };
  // 批量导出用户信息
  const handleExport = async (values:API.User[]) => {
    const res = await exportExcelUserUsingPost({user:values});
      message.success('信息导出成功！')
  }
  /**
   * 表格列配置
   */
  const columns: ProColumns<API.User>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '用户名',
      dataIndex: 'userAccount',
      valueType: 'text',
    },
    {
      title: '头像',
      dataIndex: 'userAvatar',
      valueType: 'image',
      fieldProps: {
        width: 64,
      },
      hideInSearch: true,
    },
    {
      title: '个人简介',
      dataIndex: 'userProfile',
      valueType: 'textarea',
    },
    {
      title: '权限',
      dataIndex: 'userRole',
      valueEnum: {
        user: {
          text: '用户',
        },
        admin: {
          text: '管理员',
        },
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size="middle">
          <Typography.Link
            onClick={() => {
              setCurrentRow(record);
              setUpdateModalVisible(true);
            }}
          >
            修改
          </Typography.Link>
          <Popconfirm
            title={'❌删除用户'}
            description="确定要删除此用户吗？"
            onConfirm={() => handleDelete([record.id])}
            okText="确定"
            cancelText="取消"
          >
             <Typography.Link type="danger">
              删除
            </Typography.Link>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.User>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="id"
        pagination={{
          pageSize: 5,
        }}
        search={{
          labelWidth: 120,
        }}
        rowSelection={{
          selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          preserveSelectedRowKeys:true,
        }}
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => {
          setSelectId(selectedRowKeys);
          setSelectRows(selectedRows);
          console.log(selectedRowKeys,selectedRows)
          return (
            <Space size={24}>
              <span>
                已选 {selectedRows.length} 项
                <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                  取消选择
                </a>
              </span>
            </Space>
          );
        }}
        tableAlertOptionRender={() => {
          return (
            <Space size={16}>
              <a onClick={()=>handleDelete(selectId)}>批量删除</a>
              <a onClick={()=>handleExport(selectRows)}>导出数据</a>
            </Space>
          );
        }}
        request={async (params, sort, filter) => {
          let createOrder = 0;
          let updateOrder = 0;
          if(sort.hasOwnProperty('createTime')){
            createOrder = sort.createTime === 'descend' ? 1 : 2;
            updateOrder = 0;
          }
          else if(sort.hasOwnProperty('updateTime')){
            createOrder = 0;
            updateOrder = sort.updateTime === 'descend' ? 1 : 2
          }
          const query = {
            userAccount: params.userAccount,
            userProfile: params.userProfile,
            userRole: params.userRole,
            createOrder,
            updateOrder,
            page: params.current,
            pageSize: params.pageSize,
          }
          const res = await listUserByPageUsingPost(query as API.UserQueryRequest);

          return {
            success: res.code === 200,
            data: res.data?.list || [],
            total:res.data?.total_count || 0,
          };
        }}
        columns={columns}
      />
      <UpdateModal
        visible={updateModalVisible}
        columns={columns}
        oldData={currentRow}
        onSubmit={() => {
          setUpdateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
      />
    </PageContainer>
  );
};
export default UserAdminPage;
